package cn.jsu.oj.dispatchServer.satellite.netty;

import cn.jsu.oj.dispatchServer.satellite.factory.Factory;
import cn.jsu.oj.dispatchServer.satellite.heart.HeartClientService;
import cn.jsu.oj.dispatchServer.satellite.netty.dispatcher.Dispatcher;
import cn.jsu.oj.dispatchServer.satellite.netty.starter.SatelliteStarter;
import cn.jsu.oj.dispatchServer.satellite.netty.starter.Starter;
import cn.jsu.oj.dispatchServer.satellite.server.Client;
import cn.jsu.oj.dispatchServer.satellite.server.SatelliteServer;
import cn.jsu.oj.dispatchServer.satellite.util.SpringUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 站点处理器
 *
 * @author shan
 * @date 2022/06/29
 */
@Slf4j
@Component("sitePointHandler")
@ChannelHandler.Sharable
public class SitePointHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    HeartClientService heartClientService;

    @Autowired
    Dispatcher packDispatcher;

    @Autowired
    SatelliteServer satelliteServer;

    public static final Map<String, Client> CLIENT_MAP = new HashMap<>(1024);

    /**
     * 通道连接
     *
     * @param context 通道处理程序上下文
     * @throws Exception 异常
     */
    @Override
    public void channelActive(ChannelHandlerContext context) throws Exception {
        log.info(context.channel().remoteAddress() + ": 已连接......");
        satelliteServer.init(context.channel());
        SatelliteStarter.activeSign = true;
        super.channelActive(context);
    }

    /**
     * 通道读取
     *
     * @param context 通道处理程序上下文
     * @param msg     消息
     * @throws Exception 异常
     */
    @Override
    public void channelRead(ChannelHandlerContext context, Object msg) throws Exception {
//        log.info(context.channel().remoteAddress() + ": 已接收......");
        packDispatcher.dispatch(context.channel(), msg);
        super.channelRead(context, msg);
    }

    /**
     * 通道中断
     *
     * @param context 通道处理程序上下文
     */
    @Override
    public void channelInactive(ChannelHandlerContext context) {
        log.error(context.channel().remoteAddress() + ": 已断开......");
        satelliteServer.getChannel().close();
        SatelliteStarter.activeSign = false;
        SatelliteStarter.verifySign = false;
        heartClientService.brokenHeart();
        Factory starterFactory = (Factory) SpringUtil.getBean("starterFactory");
        ((Starter) Objects.requireNonNull(starterFactory).getProduct((short) 1)).start();
        ((Starter) Objects.requireNonNull(starterFactory).getProduct((short) 2)).start();
    }
}
